<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Home\CreateOrderAddress;
use App\Http\Controllers\Home\ShowLinksController;
use App\Http\Controllers\Home\ShopCartController;
use App\Http\Controllers\Api\IndexApi;
use App\Model\Goods;
use App\Model\Goodsbrand;
use App\Model\Goodspic;
use App\Model\Goodssale;
use App\Model\Goodsspecs;
use App\Model\Goodstype;
use App\Model\HomeUserAddress;
use App\Model\AdminOrder;
use App\Model\Orderdetail;
use App\Model\Goodsattr;
use App\Model\HomeUserScores;
use App\Model\GoodsCart;
use DB;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Redis;
use App\Jobs\RollbackOrder;
use App\Jobs\SaleOrderQueue;
use Carbon\Carbon;

/**
 *这个类主要处理订单页面对地址的增删改查
 *@author guoguo<[gaymbiu@163.com]>
 */
class OrderAddressController extends Controller
{
    /**
     * Display a listing of the resource.
     * 用来处理用户选中的商品数据以UID存入redis并显示在订单确认页面，同时删除redis中sessionid存储的已进入订单的数据
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $uid = session('Homeuser-data')['id'];
        $session_id = session()->getId();
        $cartGoods = 'user_cart_attrid_set_'.$session_id;//redis中储存的是用户session_id的购物车商品属性id信息的集合
        $cartKey = 'user_cart_attrid_num_hash_'.$session_id;//redis中储存的是用户sessid的商品属性id和对应的数量
        $cartGoodsInfoKey = 'user_cart_attrid_detail_hash_';//redis中跟sessionid和attrid拼接，存储该用户sessid的购物车对应商品的详情
        $cartSelectedGoodsId_userId = Redis::hGetAll('cartSelectedGoodsId_userId_'.$uid);//用户在购物车中已选的商品属性id信息，即将显示在订单确认界面

        //取出该用户的收件人信息,如果该用户收件人信息为空，就让用户直接跳转到个人中心页面
        $userAddressArray = HomeUserAddress::select('getname', 'phone', 'address', 'whether_address', 'ssq', 'id')
                            ->where('user_id', $uid)
                            ->get()
                            ->toArray();

        if (empty($userAddressArray)) {
            // echo "<script>alert('您还没有收货地址，请先添加收货地址再下单！')</script>";
            return redirect()->route('user.address');
        }
        //在把redis中以sessionid存储的商品信息删除前，先把redis中sessionid的所有商品信息加入购物车
        $cartGoodsArray = redis::sMembers($cartGoods);
        $cartData = [];
        foreach ($cartGoodsArray as $attr_id) {
            //模型关联用的多，储存起来减轻数据库的压力
            $attrs = Goodsattr::find($attr_id);
            $attrs_goodsinfo = $attrs->goods;

            //判断选中的商品的库存是否足够
            if ($attrs->reserve < Redis::hGet($cartKey, $attr_id)) {
                echo "<script>alert('库存不够啦，减少一点购物车的数量吧！');</script>";
                exit;
            }

            if ($attrs_goodsinfo->promate == 1) {
                $price = $attrs_goodsinfo->sales->promate_price;
            } else {
                $price = $attrs_goodsinfo->price;
            }

            $cartData[$attr_id] = [
                'user_id'    => $uid,
                'goods_id'   => $attrs_goodsinfo->id,
                'attr_id'    => $attr_id,
                'goods_name' => $attrs_goodsinfo->goods_name,
                'goods_pic'  => $attrs_goodsinfo->goods_pic,
                'price'      => $price,
                'buy_num'    => Redis::hGet($cartKey, $attr_id),
                 'color'     => $attrs->color,
                 'size'      => $attrs->size,
                 'addtime'   => time(),
            ];

            //遍历出完整的一条数据后插入购物车数据库
            GoodsCart::insert($cartData[$attr_id]);
        }

        //此时即将显示在订单的数据是从数据库拿，因为已经有UID，不再使用sessionid
        $cartSelectedGoods = [];
        $total = 0;//总价
        $count = 0;//总数量
        foreach (Redis::hKeys('cartSelectedGoodsId_userId_'.$uid) as $id) {
            //模型关联用的多，储存起来减轻数据库的压力
            $attrs = Goodsattr::find($id);
            $attrs_goodsinfo = $attrs->goods;
            if ($attrs_goodsinfo->promate == 1) {
                $price = $attrs_goodsinfo->sales->promate_price;
            } else {
                $price = $attrs_goodsinfo->price;
            }
            $cartSelectedGoods[$id] = [
                'brand'    => $attrs_goodsinfo->brands->brand_name,
                'name'     => $attrs_goodsinfo->goods_name,
                'desc'     => $attrs_goodsinfo->specs->goods_desc,
                'color'    => $attrs->color,
                'size'     => $attrs->size,
                'pic'      => $attrs_goodsinfo->goods_pic,
                'num'      => Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
                'goods_id' => $attrs_goodsinfo->id,
                'price'    => $price,
                'money'    => $price * Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
            ];
            $count += $cartSelectedGoods[$id]['num'];
            $total += $cartSelectedGoods[$id]['money'];

            //在删除之前防止用户重复回退至确认订单界面而商品已经被清除导致的bug
            if (empty($cartSelectedGoods)) {
                echo "<script> alert('订单已经没有商品信息了,去订单列表瞅瞅??');location.href='/Home'; </script>";
            }
            //上面的数据是以UID存储在redis中，所以不用担心用户切换浏览器清除cookie，
            // 可以删掉redis中该用户sessionid的已选中的商品数据,每遍历出一个就删掉一个
            Redis::del($cartGoodsInfoKey.$session_id.'_'.$id);
            Redis::hDel($cartKey, $id);
            Redis::sRem($cartGoods, $id);
        }


        // dd(Redis::hGetAll($cartKey);//这里面剩下的都是未选中的商品数据

        //获取购物车数量显示在购物车标志上
        $shopCartController = new ShopCartController;
        $originalNum = $shopCartController->showCartNumber();//购物车数量

        $member = session('Homeuser-data')['member'];//会员等级

        //根据会员等级决定享受不同的折扣
        switch ($member) {
            case 1:
                $discount = 0.005;
                break;
            case 2:
                $discount = 0.01;
                break;
            case 3;
                $discount = 0.015;
                break;
            default:
                $discount = 0;
        }

        $discountMoney = $total * $discount;//会员优惠金额
        $payment = 6;//运费

        // 查出用户的积分
        $scores = DB::table('shop_user_socres')->select('scores')->where('user_id', $uid)->get()->toArray();
        if (!$scores) {
            $score = 0;
        } else {
            $score = $scores[0]->scores;
        }
        // 积分兑换比例查redis
        $prop = Redis::get('shop-score-rule');
        //积分可兑换的额度
        $scoreToMoney = $score * $prop;
        //减额总量
        $totalDiscount = $discountMoney + $scoreToMoney;
        //总付金额
        $totalPay = $total + $payment - $scoreToMoney - $discountMoney;

        // 友情链接
        $showLinks = new ShowLinksController;
        $linksArray = $showLinks->index();

        //查询站点信息.
        $sate = IndexApi::getSate();

        // 查出默认地址
        $defaultAddress = DB::table('shop_user_addresses')
                            ->select('getname', 'phone', 'ssq', 'address')
                            ->where('whether_address', 1)
                            ->where('user_id', $uid)
                            ->first();

        //引入站点信息
        $sate = IndexApi::getSate();

        //将用户选中的购物车的详细数据和用户的收货信息传递到前台
        return view('Home.goods-order', [
            'cartSelectedGoods' => $cartSelectedGoods,
            'userAddressArray'  => $userAddressArray,
            'total'             => $total,
            'count'             => $count,
            'originalNum'       => $originalNum,
            'member'            => $member,
            'payment'           => $payment,
            'discount'          => $discount,
            'discountMoney'     => $discountMoney,
            'score'             => $score,
            'scoreToMoney'      => $scoreToMoney,
            'totalDiscount'     => $totalDiscount,
            'totalPay'          => $totalPay,
            'linksArray'        => $linksArray,
            'sata'              => $sate,
            'defaultAddress'    => $defaultAddress,
            'sate'              => $sate,
        ]);

    }

    /**
     * Show the form for creating a new resource.
     *  负责生成用户确认收货信息提交的订单，
     * @return \Illuminate\Http\Response
     */
    public function createOrder(Request $request)
    {
        //接收用户是否选择了抵扣积分
        $scoreStatus = intval($request->input('scores'));

        $uid = session('Homeuser-data')['id'];
        $session_id = session()->getId();
        $cartGoods = 'user_cart_attrid_set_'.$session_id;//redis中储存的是用户session_id的购物车商品属性id信息的集合
        $cartKey = 'user_cart_attrid_num_hash_'.$session_id;//redis中储存的是用户sessid的商品属性id和对应的数量
        $cartGoodsInfoKey = 'user_cart_attrid_detail_hash_';//redis中跟sessionid和attrid拼接，存储该用户sessid的购物车对应商品的详情
        $cartSelectedGoodsId_userId = Redis::hGetAll('cartSelectedGoodsId_userId_'.$uid);//用户在购物车中已选的商品属性id信息，即将显示在订单确认界面

        //如果用户支付完成后返回上一级页面，会因为之前生成订单存在于redis中的
        // 'cartSelectedGoodsId_userId_'.$uid已经被删除，导致订单空白的情况
        // 所以先检查这个redis键是否存在，不存在的话取出的值就是空，就直接返回首页
        if (!$cartSelectedGoodsId_userId) {
            echo "<script>alert('订单已经生成啦，赶快去订单页查看购买的宝贝吧！');</script>";
            // echo "<script>alert('订单已经支付过啦')</script>";
            return redirect()->route('orderlist');
        }

        //取出订单用户的数据，
        $cartSelectedGoods = [];
        $names = '';
        $total = 0;//总价
        $count = 0;//总数量
        foreach (Redis::hKeys('cartSelectedGoodsId_userId_'.$uid) as $id) {
            //模型关联用的多，储存起来减轻数据库的压力
            $attrs = Goodsattr::find($id);
            $attrs_goodsinfo = $attrs->goods;
            if ($attrs_goodsinfo->promate == 1) {
                $price = $attrs_goodsinfo->sales->promate_price;
            } else {
                $price = $attrs_goodsinfo->price;
            }
            $cartSelectedGoods[$id] = [
                'attr_id'   => $id,
                'name'      => $attrs_goodsinfo->goods_name,
                'pic'       => $attrs_goodsinfo->goods_pic,
                'price'     => $price,
                'num'       => Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
                'money'     => $price * Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
            ];
            $names .= $cartSelectedGoods[$id]['name'].' / ';
            $total += $cartSelectedGoods[$id]['money'];
        }


        //找到用户的默认地址，作为订单的收件人信息
        //取出该用户的收件人信息
        $getMsg = HomeUserAddress::select('getname', 'phone', 'address', 'ssq')
                            ->where('user_id', $uid)
                            ->where('whether_address', 1)
                            ->get()
                            ->toArray();

        $getName = $getMsg[0]['getname'];//收件人
        $address = $getMsg[0]['ssq'].$getMsg[0]['address'];
        $phone = $getMsg[0]['phone'];

        $member = session('Homeuser-data')['member'];//会员等级
        $discount = 0.01;//会员折扣
        $discountMoney = $total * $discount;//会员优惠金额
        $payment = 6;//运费

        // 查出用户的积分
        $scores = DB::table('shop_user_socres')->select('scores')->where('user_id', $uid)->get()->toArray();
        if (!$scores) {
            $score = 0;
        } else {
            $score = $scores[0]->scores;
        }
        // 积分兑换比例查redis
        $prop = Redis::get('shop-score-rule');

        //根据是否选择了积分抵扣金额而计算总价
        if ($scoreStatus == 1) {
            //选择了抵扣积分
            $scoreToMoney = $score * $prop;

        } else {
            $scoreToMoney = 0;
        }

        // 友情链接
        $showLinks = new ShowLinksController;
        $linksArray = $showLinks->index();

        //总减额
        $totalDiscount = $discountMoney + $scoreToMoney;
        //总付金额
        $totalPay = $total + $payment - $totalDiscount;


        $order = [];
        $order['user_id'] = $uid;
        $order['o_num'] = $uid.time();
        $order['getname'] = $getName;
        $order['address'] = $address;
        $order['phone'] = $phone;
        $order['status'] = 1;
        $order['message'] = '';
        $order['discount'] = $discountMoney;
        $order['score'] = $scoreToMoney;
        $order['total'] = $totalPay;
        $order['create_at'] = date('Y-m-d H:i:s');

        //到这里，订单表所需的数据都齐全可以插入订单表和订单详情表
        //减库存，扣掉使用的积分，支付以后就增加产生的积分，判断是否满足会员升级
        DB::beginTransaction();
        try {
            // 将订单信息存入订单表
            $orderId = AdminOrder::insertGetId($order);

            //拿到订单id后将订单详情存入详情表
            $cartSelectedGoods = [];
            foreach (Redis::hKeys('cartSelectedGoodsId_userId_'.$uid) as $id) {
                //模型关联用的多，储存起来减轻数据库的压力
                $attrs = Goodsattr::find($id);
                $attrs_goodsinfo = $attrs->goods;
                if ($attrs_goodsinfo->promate == 1) {
                    $price = $attrs_goodsinfo->sales->promate_price;
                } else {
                    $price = $attrs_goodsinfo->price;
                }

                //每遍历出一个确认买的数据就从购物车表里面删除一个
                GoodsCart::where('attr_id', $id)
                         ->where('user_id', $uid)
                         ->delete();

                $cartSelectedGoods[$id] = [
                    'order_id'  => $orderId,
                    'attr_id'   => $id,
                    'picurl'    => $attrs_goodsinfo->goods_pic,
                    'gname'     => $attrs_goodsinfo->goods_name,
                    'buynum'    => Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
                    'price'     => $price,
                    'desc'      => $price * Redis::hGet('cartSelectedGoodsId_userId_'.$uid, $id),
                ];

                //减库存
                Goodsattr::where('id', $id)->decrement('reserve', $cartSelectedGoods[$id]['buynum']);

                //加销量
                Goods::where('id', Goodsattr::find($id)->goods->id)->increment('buy_num', $cartSelectedGoods[$id]['buynum']);

                //加经验
                DB::table('shop_user_members')->where('user_id', $uid)->increment('exp', $totalPay);

                //插入详情表
                Orderdetail::insert($cartSelectedGoods[$id]);
            }

            //如果有使用积分就扣掉购买所消耗的积分
            if ($scoreStatus == 1) {

                HomeUserScores::where('user_id', $uid)->update(['scores' => 0]);

            }

            // 累加上用户本次购买所产生的积分
            HomeUserScores::where('user_id', $uid)->increment('scores', $totalPay);

            DB::commit();
        } catch(\Illuminate\Database\QueryException $e) {
            //回滚事务
	    	DB::rollback();

            return back()->with('系统繁忙，稍后再试');
        }

        //获取购物车数量显示在购物车标志上
        $shopCartController = new ShopCartController;
        $originalNum = $shopCartController->showCartNumber();//购物车数量

        Redis::del('cartSelectedGoodsId_userId_'.$uid);

        RollbackOrder::dispatch($orderId)->delay(Carbon::now()->addMinutes(30));

        //查询站点信息
        $sate = IndexApi::getSate();

        return view('Home.goods-orderSuccess', [
            'getMsg' => $getMsg[0],
            'names' => $names,
            'o_num' => $order['o_num'],
            'totalPay' => $totalPay,
            'orderId' => $orderId,
            'originalNum' => $originalNum,
            'linksArray' => $linksArray,
            'sate'   => $sate,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     * 用户在确认订单收货信息点击支付的时候通过AJAX传递订单id过来，改订单的状态为待发货
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response 返回的是支付结果，404为失败，200为成功
     */
    public function orderPay(Request $request)
    {
        //获取传递过来的订单id
        $oid = $request->oid;
        $uid = session('Homeuser-data')['id'];

        // 检查该用户对应的该订单id是否存在以及是否为待支付状态
        $res = AdminOrder::select('status')
                         ->where('user_id', $uid)
                         ->where('id', $oid)
                         ->first()
                         ->toArray();
        if (!$res || $res['status'] != 1) {
            return response()->json([
                'status' => '404',
                'msg' => '订单异常，请联系管理员~！',
            ]);
        }

        //走到这里说明订单正常，再把订单状态改为待发货
        DB::table('shop_orders')
                  ->where('user_id', $uid)
                  ->where('id', $oid)
                  ->update(['status' => 4, 'pay_at' => date('Y-m-d H:i:s')]);

        return response()->json([
            'status' => 200,
            'msg' => '支付成功，您的包裹整装待发',
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     * 通过前台AJAX传递的id编辑用户的收货地址
     * @return \Illuminate\Http\Response
     */
    public function editAddress(CreateOrderAddress $request)
    {
        //接收传递过来的数据
        $getName = $request->getname;
        $province = $request->province;
        $city = $request->city;
        $area = $request->area;
        $ssq = $province.$city.$area;
        $address = $request->addressdetail;
        $phone = $request->phone;
        $id = $request->id;
        $user_id = session('Homeuser-data')['id'];
        $userInfo = HomeUserAddress::find($id)->toArray();
        $whether_address = $userInfo['whether_address'];
        //判断用户和被改的数据的主人是同一个人
        if ($userInfo['user_id'] != $user_id) {
            return response()->json([
                'status' => 403,
                'msg' => '不要瞎几把改别人的数据'
            ]);
        }

        //走到这里说明一切数据都合法，准备在数据库编辑数据
        $res = DB::table('shop_user_addresses')
                ->where('id', $id)
                ->update([
                    'getname' => $getName,
                    'phone' => $phone,
                    'address' => $address,
                    'whether_address' => $whether_address,
                    'ssq' => $ssq,
                ]);

        if (!$res) {
            return response()->json([
                'status' => 404,
                'msg' => '数据没有任何变化',
            ]);
        }

        //来到这里说明更改成功，返回数据
        return response()->json([
            'status' => 200,
            'getname' => $getName,
            'ssq' => $ssq,
            'phone' => $phone,
            'address' => $address,
        ]);
    }

    /**
     * Update the specified resource in storage.
     * 接收前台用户AJAX传递过来的id修改地址的默认状态
     * @return \Illuminate\Http\Response 返回的是状态码404表示失败，
     * 200表示成功
     */
    public function defaultAddress(Request $request)
    {
        $id = $request->id;
        $uid = session('Homeuser-data')['id'];

        //将同一用户下的其他默认地址状态改为非默认的
        $notDefault = DB::table('shop_user_addresses')
                    ->where('user_id', $uid)
                    ->where('whether_address', 1)
                    ->whereNotIn('id',[$id])
                    ->update(['whether_address' => 2]);

        if (!$notDefault) {
            return response()->json([
                'status' => 403,
                'msg' => '修改失败1',
            ]);
        }

        //来到这里说明其他的默认状态的地址已经改为非默认的了,再把本id改为默认的
        $toDefault = DB::table('shop_user_addresses')
                   ->where('user_id', $uid)
                   ->where('id', $id)
                   ->update(['whether_address' => 1]);

        if (!$toDefault) {
            return response()->json([
                'status' => 404,
                'msg' => '修改失败2',
            ]);
        }

        //来到这里，万事OK
        return response()->json([
            'status' => 200,
            'msg' => '修改成功',
        ]);


    }

    /**
     * Remove the specified resource from storage.
     * 接收前台AJAX传递过来的id删掉用户的地址信息
     * @return \Illuminate\Http\Response 返回的是状态码，200代表删除成功，404失败
     */
    public function deleteAddress(Request $request)
    {
        $id = intval($request->id);
        if ($id < 1) {
            return response()->json([
                'status' => 403,
                'msg' => '删除失败',
            ]);
        }

        //判断防止用户改id删除别人的地址,在登录用户的id里面查传过来的地址id，如果没找到就不给删
        $user_id = session('Homeuser-data')['id'];
        $res = HomeUserAddress::find($id)->toArray();
        if ($res['user_id'] != $user_id) {
            return response()->json([
                'status' => 404,
                'msg' => '不要乱动',
            ]);
        } else{
            //走到这里说明证据合法,删掉地址数据
            DB::table('shop_user_addresses')
                ->where('id', $id)
                ->delete();
            return response()->json([
                'status' => 200,
                'msg' => '删除成功',
            ]);

        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function linkstest()
    {
        $showLinks = new ShowLinksController;
        $linksArray = $showLinks->index();
        return view('Home/goods-order', ['linksArray' => $linksArray]);
    }

    /**
     * Remove the specified resource from storage.
     * 用户在购物车界面点击结算，获取用户选中的商品属性id
     * @return \Illuminate\Http\Response
     */
    public function getCartGoods(Request $request)
    {
        //判断用户是否有登录，没登录就返回到登录界面
        if (empty(session('Homeuser-data'))) {
            return response()->json([
                'status' => 404,
                'msg' => '未登录,请先登录',
            ]);
        }



        $attr_ids = $request->attr_ids;
        if (!$attr_ids) {
            return response()->json([
                'status' => 403,
                'msg' => '存档失败，请先添加商品到购物车'
            ]);
        }

        //来到这里说明用户已经登录，接下来准备将用户的购物车数据存入购物车数据表,先拿到登录用户的uid
        $user_id = session('Homeuser-data')['id'];

        //判断用户有没有收货地址，如果没有就跳转到个人中心编辑地址页
        $addressInfo = DB::table('shop_user_addresses')
                         ->select('getname')
                         ->where('user_id', $user_id)
                         ->where('whether_address', 1)
                         ->first();

        if (!$addressInfo) {
            return response()->json([
                'status' => 402,
                'msg' => '没有收件地址，先添加一个收货地址吧~',
            ]);
        }

        //拿到拼接后的id字符串后，去掉末尾的逗号变成数组
        // $attr_idsArray = explode(',', substr($attr_ids, 0, strlen($attr_ids) - 1));
        // $attr_idsArray = explode(',', substr($attr_ids, 0, -1));
        $attr_idsArray = explode(',', rtrim($attr_ids, ','));

        $session_id = session()->getId();
        $cartGoods = 'user_cart_attrid_set_'.$session_id;//redis中储存的是用户的购物车商品属性id信息的集合
        $cartKey = 'user_cart_attrid_num_hash_'.$session_id;//redis中储存的是用户的商品属性id和对应的数量
        $cartGoodsInfoKey = 'user_cart_attrid_detail_hash_';//redis中跟sessionid和attrid拼接，存储该用户的购物车对应商品的详情

        $cartAttridArray = Redis::sMembers($cartGoods);
        foreach ($cartAttridArray as $v) {
          $lastId = DB::table('shop_goods_carts')->insertGetId([
              'user_id' => $user_id,
              'goods_id' => Goodsattr::find($v)->goods->id,
              'attr_id' => $v,
              'goods_name' => Redis::hGet($cartGoodsInfoKey.$session_id.'_'.$v, 'name'),
              'goods_pic' => Redis::hGet($cartGoodsInfoKey.$session_id.'_'.$v, 'pic'),
              'price' => Redis::hGet($cartGoodsInfoKey.$session_id.'_'.$v, 'price'),
              'buy_num' => Redis::hGet($cartKey, $v),
              'color' => Redis::hGet($cartGoodsInfoKey.$session_id.'_'.$v, 'color'),
              'size' => Redis::hGet($cartGoodsInfoKey.$session_id.'_'.$v, 'size'),
              'addtime' => time(),
          ]);
        }


        if (!$lastId) {
            return response()->json([
                'status' => 403,
                'msg' => '存档失败，请先添加商品到购物车'
            ]);
        }

        //在将选中的商品信息存入redis前先删除该用户以uid存储的之前的已选商品信息
        Redis::del('cartSelectedGoodsId_userId_'.$user_id);

        //将用户的选中商品id存入redis，在下一个控制器中方便拿出来'cartSelectedGoodsId_userId_'.$user_id哈希
        foreach ($attr_idsArray as $v) {
            Redis::hMset('cartSelectedGoodsId_userId_'.$user_id, $v, Redis::hGet($cartKey, $v));
        }

        return response()->json([
            'status' => 200,
            'msg' => '下单成功，快去核对收货信息吧~',
        ]);

    }

    /**
     * Remove the specified resource from storage.
     * 检查用户点击的是促销商品，获取用户选中的商品属性id，
     * @return \Illuminate\Http\Response
     */
    public function confirmSale(Request $request)
    {
        // 检查有没有登录
        if (empty(session('Homeuser-data'))) {
            return response()->json([
                'status' => 100,
                'msg' => '请先登陆',
            ]);
        }

        // 检查用户有没有收货信息，没有的话就跳到个人中心地址管理页面
        $addressInfo = HomeUserAddress::select('getname')
                                      ->where('whether_address', 1)
                                      ->where('user_id', session('Homeuser-data')['id'])
                                      ->first();

        if (!$addressInfo) {
            return response()->json([
                'status' => 345,
                'msg'    => '您还没有收货地址，先添加收货地址再抢购吧~',
            ]);
        }

        //模型关联用的多，储存起来减轻数据库的压力
        $attr_id = $request->attr_id;
        $attrs = Goodsattr::find($attr_id);
        $attr_goodsinfo = $attrs->goods;

        //拿到商品的属性id，和用户的UID，先判断是否还有库存 以及是否是促销商品
        $reserve = $attrs->reserve;
        $isPromate = $attr_goodsinfo->promate;
        $promate_num = $attr_goodsinfo->sales->promate_num;

        if ($reserve < 1 || $isPromate != 1 || $promate_num == 0) {
            return response()->json([
                'status' => 403,
                'msg' => '抱歉，商品已售罄，看看别的吧',
            ]);
        }

        return response()->json([
            'status'  => 200,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     * 传过来的属性id去查询详情和提取用户的地址信息遍历到订单页面
     * @return \Illuminate\Http\Response
     */
    public function saleOrder(Request $request)
    {

        $attr_id = $request->attr_id;

        //模型关联用的多，储存起来减轻数据库的压力,先判断是否存在该商品
        $attrs = Goodsattr::find($attr_id);
        if (!$attrs) {
            return redirect()->route('Home.index');
        }

        $attr_goodsinfo = $attrs->goods;
        $uid = session('Homeuser-data')['id'];

        //判断是否是促销以及促销数量不能小于1
        $isPromate = $attr_goodsinfo->promate;
        $promate_num = $attr_goodsinfo->sales->promate_num;
        if ($isPromate != 1 || $promate_num < 1) {
            return redirect()->route('Home.index');
        }

        //提取用户收件信息
        $getMsg = HomeUserAddress::select('getname', 'phone', 'ssq', 'address', 'whether_address', 'id')
                                 ->where('user_id', $uid)
                                 ->get()
                                 ->toArray();

        //如果没有收货信息就提示用户没有收货信息，在详情页面js跳转到个人中心////////////////////////////////////////黎总的详情页面跳转///////////////////////////////////////////
        if (empty($getMsg)) {
            return redirect()->route('user.address');
        }

        //运费
        $payMent = 6;
        //促销价
        $sale = Goodssale::select('promate_price')->where('goods_id', $attr_goodsinfo->id)->first()->toArray();
        $salePrice = $sale['promate_price'];

        $attrs_goodsinfo = [
            'goods_name' => $attr_goodsinfo->goods_name,
            'goods_pic'  => $attr_goodsinfo->goods_pic,
            'id'         => $attr_goodsinfo->id,
            'color'      => $attrs->color,
            'size'       => $attrs->size,
            'brand'      => Goodsbrand::find($attr_goodsinfo->brand_id)->brand_name,
        ];

        // 友情链接
        $showLinks = new ShowLinksController;
        $linksArray = $showLinks->index();

        //查询站点信息
        $sate = IndexApi::getSate();

        //将商品信息带到页面显示出来，将属性id和用户id传递到提交订单的AJAX按钮
        return view('Home/goods-sale-order', [
            'attrs_goodsinfo' => $attrs_goodsinfo,
            'salePrice'  => $salePrice,
            'getMsg'     => $getMsg,
            'attr_id'    => $attr_id,
            'uid'        => $uid,
            'totalPay'   => $salePrice + $payMent,
            'payment'    => $payMent,
            'linksArray' => $linksArray,
            'sate'       => $sate,
        ]);

    }

    /**
     * Remove the specified resource from storage.
     * 接收确认订单POST传递过来的留言数据
     * @return \Illuminate\Http\Response
     */
    public function createSaleOrder(Request $request)
    {
        $attr_id = $request->input('attr_id');
        $message = $request->input('message');
        $attrs = Goodsattr::find($attr_id);
        $attr_goodsinfo = $attrs->goods;
        $promate_num = $attr_goodsinfo->sales->promate_num;
        $gid = $attr_goodsinfo->id;

        //当前用户的uid
        $uid = session('Homeuser-data')['id'];

        //模型关联用的多，储存起来减轻数据库的压力
        $attrs = Goodsattr::find($attr_id);

        //不存在该商品就回首页
        if (!$attrs) {
            return redirect()->route('Home.index');
        }
        $p_num = Redis::hGet('goods_sale_hash_data:'.$gid, 'promate_num');

        if ($promate_num == 0 || Redis::lLen('goods_sale_order_queue_data:'.$gid) == $p_num) {

            $url = $_SERVER['SCRIPT_NAME'];
            echo "<script>alert('该商品以被抢光，请选购其他商品！');location.href='".$url."/Home'</script>";
            exit;
        }


        $price = $attr_goodsinfo->sales->promate_price;
        // //取出当前用户的收件信息
        $getMessage = HomeUserAddress::select('getname', 'phone', 'ssq', 'address')
                                     ->where('user_id', $uid)
                                     ->where('whether_address', 1)
                                     ->first()
                                     ->toArray();

        //判断提交过来的商品属性id是否合法以及促销余量不能小于1
        $isPromate = $attr_goodsinfo->promate;
        $promate_num = $attr_goodsinfo->sales->promate_num;
        if ($isPromate != 1) {
            return redirect()->route('Home.index');
        }

        //走到这里说明商品数据合法正常,判断促销订单队列的个数是否大于促销数量
        $listKey = 'goods_sale_order_queue_data:'.$gid;

        if (Redis::lLen($listKey) < $promate_num) {

            //将用户id存入促销队列
            Redis::lPush($listKey, $uid);
            sleep(1);

            if(Redis::lLen($listKey) <= $promate_num) {
                while($user_id = Redis::rPop($listKey)) {

                    $getMsg = HomeUserAddress::select('getname', 'phone', 'ssq', 'address')
                                             ->where('user_id', $user_id)
                                             ->where('whether_address', 1)
                                             ->first();

                    $order = [
                        'user_id'   => $uid,
                        'o_num'     => $uid.time(),
                        'getname'   => $getMsg['getname'],
                        'address'   => $getMsg['ssq'].$getMsg['address'],
                        'phone'     => $getMsg['phone'],
                        'status'    => 1,
                        'message'   => '促销不留言',
                        'create_at' => date('Y-m-d H:i:s'),
                        'total'     => $price,
                        'discount'  => 0,
                        'score'     => 0,
                    ];

                    //到这里，订单表所需的数据都齐全可以插入订单表和订单详情表
                    DB::beginTransaction();
                    try {
                        // 将订单信息存入订单表
                        $orderId = AdminOrder::insertGetId($order);

                        //拿到订单id后将订单详情存入详情表
                        $orderDetail = [
                            'order_id'  => $orderId,
                            'attr_id'   => $attr_id,
                            'picurl'    => $attr_goodsinfo->goods_pic,
                            'gname'     => $attr_goodsinfo->goods_name,
                            'buynum'    => 1,
                            'price'     => $price,
                            'desc'      => $price,
                        ];

                        //减库存
                        Goodsattr::where('id', $attr_id)->decrement('reserve', 1);

                        //减促销量
                        Goodssale::where('goods_id', $gid)->decrement('promate_num', 1);

                        //加销量
                        Goods::where('id', $gid)->increment('buy_num', 1);

                        //插入详情表
                        Orderdetail::insert($orderDetail);

                        DB::commit();
                    } catch(\Illuminate\Database\QueryException $e) {
                        //回滚事务
            	    	DB::rollback();

                        return back()->with('系统繁忙，稍后再试');
                    }

                    //获取购物车数量显示在购物车标志上
                    $shopCartController = new ShopCartController;
                    $originalNum = $shopCartController->showCartNumber();//购物车数量

                    Redis::del('cartSelectedGoodsId_userId_'.$uid);

                    SaleOrderQueue::dispatch($orderId)->delay(Carbon::now()->addMinutes(5));

                    sleep(0.5);
                }
            }
        $o_numArray = DB::table('shop_orders')
                        ->select('o_num')
                        ->where('id', $orderId)
                        ->first();

        $o_num = $o_numArray->o_num;

        //获取购物车数量显示在购物车标志上
        $shopCartController = new ShopCartController;
        $originalNum = $shopCartController->showCartNumber();//购物车数量

        // 友情链接
        $showLinks = new ShowLinksController;
        $linksArray = $showLinks->index();

        //查询站点信息
        $sate = IndexApi::getSate();

        return view('Home.goods-orderSuccess', [
            'getMsg'      => $getMessage,
            'names'       => $attr_goodsinfo->goods_name,
            'o_num'       => $o_num,
            'totalPay'    => $price,
            'orderId'     => $orderId,
            'originalNum' => $originalNum,
            'linksArray'  => $linksArray,
            'sate'        => $sate,
        ]);

        } else {

            return back()->with('message', '该促销商品已被抢光');
        }

        // 将订单的商品属性id以及用户的UID存入redis队列
    }

}
